//
//  SoundTool.m
//  83打飞机
//
//  Created by chi on 14-8-5.
//  Copyright (c) 2014年 xiaoming. All rights reserved.
//

#import "SoundTool.h"

#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>


static SoundTool *sharedSoundTool;

@interface SoundTool ()


/*** 音乐播放器 */
@property (nonatomic, strong) AVAudioPlayer *player;

/*** 音效字典 */
@property (nonatomic, strong) NSMutableDictionary *soundDict;



@end

@implementation SoundTool

+ (void)initialize
{
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategorySoloAmbient error:nil];
    [session setActive:YES error:nil];
    
}

+ (id)allocWithZone:(struct _NSZone *)zone
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedSoundTool = [super allocWithZone:zone];
    });
    
    return sharedSoundTool;
}

+ (instancetype)sharedSoundTool
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedSoundTool = [[SoundTool alloc]init];
    });
    
    return sharedSoundTool;
}


/**
 *  加载systemsoundId
 */
- (SystemSoundID)loadSystemSoundIDByFileName:(NSString*)fileName WithBundle:(NSBundle*)bundle
{
    SystemSoundID sysID;
    
    NSString *path;
    
    if (bundle == nil) {
        path = [[NSBundle mainBundle] pathForResource:fileName ofType:@"wav"];
    }
    else {
        path = [bundle pathForResource:fileName ofType:@"wav"];
    }
    
    
    NSURL *url = [[NSURL alloc]initFileURLWithPath:path];
    
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)(url), &sysID);
    
    return sysID;
}

/**
 *  把systemsoundid加入字典
 */
- (void)loadSoundDictionaryWithBundle:(NSBundle*)bundle
{
    NSArray *array = @[@"msgcome"];
    
    self.soundDict = [NSMutableDictionary dictionaryWithCapacity:array.count];
    
    for (NSString *name in array) {
        
        SystemSoundID sysID = [self loadSystemSoundIDByFileName:name WithBundle:bundle];
        
        
        [self.soundDict setObject:@(sysID) forKey:name];
    }
    
    
    
}


- (id)init
{
    if (self = [super init]) {
        
        NSString *musicPath = [[NSBundle mainBundle] pathForResource:@"silence" ofType:@"mp3"];

        
        NSURL *url = [[NSURL alloc]initFileURLWithPath:musicPath];
        

//        self.player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
//        [self.player setNumberOfLoops:-1];
//        [self.player prepareToPlay];
        
        [self loadSoundDictionaryWithBundle:nil];
        
    }
    
    
    
    return self;
}



/**
 *  播放
 */
- (void)playBackgroundMusic
{
    [self.player play];
}

/**
 *  暂停
 */
- (void)pauseBackgroundMusic
{
    [self.player pause];
}

/**
 *  停止
 */
- (void)stopBackgroundMusic
{
    [self.player stop];
}


/**
 *  播放音效
 */
- (void)playSoundByFileName:(NSString *)fileName
{
    SystemSoundID sysID = [self.soundDict[fileName] unsignedLongValue];
    
    AudioServicesPlaySystemSound(sysID);
}


@end
